/*
smzdm 签到脚本
项目地址: https://github.com/hex-ci/smzdm_script

cron: 10 8 * * *
*/
/*
const Env = require('./env');
const { SmzdmBot, requestApi, removeTags, getEnvCookies } = require('./bot');
const fs = require("fs");
const path = require('path');
const { getRandom, sleep ,bark } = require("./lib/utils"); //工具类
*/

import Env from './env.js'
import { SmzdmBot, requestApi, removeTags , config} from './bot.js'
import notify  from './sendNotify.js'

// ------------------------------------

const $ = new Env('smzdm评论分享点赞收藏');

class SmzdmIntegralBot extends SmzdmBot {
  constructor(user) {
    super(user);

    this.commentlist=user.commentlist;
  }

  async run() {

    const articles = await this.getArticleList(20);

    if (articles.length < 1) {
      return {
        isSuccess: false
      };
    }
    for(let i=0;i<5;i++)
    {
        // 随机选一篇文章来评论
        const article = articles[Math.floor(Math.random() * articles.length)];
        const comment = this.commentlist[Math.floor(Math.random() * this.commentlist.length)];
        

        $.log('等候 5 秒');
        await $.wait(5000);
        await this.doShareTask(article);

        $.log('等候 5 秒');
        await $.wait(5000);
        await this.doFavoriteTask(article);

        $.log('等候 5 秒');
        await $.wait(5000);
        await this.doRatingTask(article);


        $.log('等候 6 秒');
        await $.wait(6000);
        await this.doCommentTask(article,comment);
    }
    return "已执行完赚积分任务：分享、点赞、评论、点值各五次！";
    /*
    const { msg: msg1 } = await this.checkin();

    const { msg: msg2 } = await this.allReward();

    const { msg: msg3 } = await this.extraReward();

    return `${msg1}${msg2}${msg3}`;
    */
  }

  // 发表评论
  async submitComment({ articleId, channelId, content }) {
    const { isSuccess, data, response } = await requestApi('https://comment-api.smzdm.com/comments/submit', {
      method: 'post',
      headers: this.getHeaders(),
      data: {
        touchstone_event: this.getTouchstoneEvent({
          event_value: {
            aid: articleId,
            cid: channelId,
            is_detail: true
          },
          sourceMode: '好物社区_全部',
          sourcePage: `Android/长图文/${articleId}/评论页/`,
          upperLevel_url: '好物社区/首页/全部/',
          sourceRoot: '社区'
        }),
        is_like: 3,
        reply_from: 3,
        smiles: 0,
        atta: 0,
        parentid: 0,
        token: this.token,
        article_id: articleId,
        channel_id: channelId,
        content
      }
    });

    if (isSuccess) {
      $.log(`评论发表成功: ${data.data.comment_ID}`);
    }
    else {
      $.log(`评论发表失败！${response}`);
    }

    return {
      isSuccess,
      data,
      response
    };
  }

  // 执行收藏任务
  async doFavoriteTask(article) {
    $.log(`开始收藏: ${article.article_title}。。`);

    let articleId = '';
    let channelId = '';

    articleId = article.article_id;
    channelId = article.article_channel_id;

    $.log('等候 3 秒');
    await $.wait(3000);

    await this.favorite({
      method: 'destroy',
      id: articleId,
      channelId
    });

    $.log('等候 3 秒');
    await $.wait(3000);

    await this.favorite({
      method: 'create',
      id: articleId,
      channelId
    });

    $.log('等候 3 秒');
    await $.wait(3000);

    await this.favorite({
      method: 'destroy',
      id: articleId,
      channelId
    });

    $.log('延迟 5 秒领取奖励');
    await $.wait(5000);
  }

  // 执行评论任务
  async doCommentTask(article,comment) {
    $.log('开始评论。。。。。。。');

        

    const {isSuccess, data } = await this.submitComment({
    articleId: article.article_id,
    channelId: article.article_channel_id,
    content: comment
    });

    if (!isSuccess) {
    return {
        isSuccess
    };
    }


    await $.wait(5000);
    $.log(`篇名为“${article.article_title}”文章评论结束。。。`);
    

  }

  // 执行点赞任务
  async doRatingTask(article) {
    $.log(`开始点赞: ${article.article_title}。。。`);

    $.log('等候 3 秒');
    await $.wait(3000);

    if (article.article_price) {
      // 点值
      await this.rating({
        method: 'worth_cancel',
        type: 3,
        id: article.article_id,
        channelId: article.article_channel_id
      });

      $.log('等候 3 秒');
      await $.wait(3000);

      await this.rating({
        method: 'worth_create',
        type: 1,
        id: article.article_id,
        channelId: article.article_channel_id
      });

      $.log('等候 3 秒');
      await $.wait(3000);

      await this.rating({
        method: 'worth_cancel',
        type: 3,
        id: article.article_id,
        channelId: article.article_channel_id
      });
    }
    else {
      // 点赞
      await this.rating({
        method: 'like_cancel',
        id: article.article_id,
        channelId: article.article_channel_id
      });

      $.log('等候 3 秒');
      await $.wait(3000);

      await this.rating({
        method: 'like_create',
        id: article.article_id,
        channelId: article.article_channel_id
      });

      $.log('等候 3 秒');
      await $.wait(3000);

      await this.rating({
        method: 'like_cancel',
        id: article.article_id,
        channelId: article.article_channel_id
      });
    }

    $.log('延迟 5 秒领取奖励');
    await $.wait(5000);
  }
  
  // 执行文章分享任务
  async doShareTask(article) {
    $.log(`开始分享第 ${article.article_title} ...`);

    await this.getArticleDetail(article.article_id);

    $.log('等候 8 秒');
    await $.wait(8000);

    await this.shareArticleDone(article.article_id, article.article_channel_id);
    await this.shareDailyReward(article.article_channel_id);
    await this.shareCallback(article.article_id, article.article_channel_id);

    $.log('等候 5 秒');
    await $.wait(5000);
  }

  // 分享完成
  async shareArticleDone(articleId, channelId) {
    const { isSuccess, response } = await requestApi('https://user-api.smzdm.com/share/complete_share_rule', {
      method: 'post',
      headers: this.getHeaders(),
      data: {
        token: this.token,
        article_id: articleId,
        channel_id: channelId,
        tag_name: 'gerenzhongxin'
      }
    });

    if (isSuccess) {
      $.log('完成分享成功。');

      return {
        isSuccess,
        msg: '完成分享成功。'
      };
    }
    else {
      $.log(`完成分享失败！${response}`);

      return {
        isSuccess: false,
        msg: '完成分享失败！'
      };
    }
  }

  // 分享完成后回调接口
  async shareCallback(articleId, channelId) {
    const { isSuccess, response } = await requestApi('https://user-api.smzdm.com/share/callback', {
      method: 'post',
      headers: this.getHeaders(),
      data: {
        token: this.token,
        article_id: articleId,
        channel_id: channelId,
        touchstone_event: this.getTouchstoneEvent({
          event_value: {
            aid: articleId,
            cid: channelId,
            is_detail: true,
            pid: '无'
          },
          sourceMode: '排行榜_社区_好文精选',
          sourcePage: `Android/长图文/P/${articleId}/`,
          upperLevel_url: '排行榜/社区/好文精选/文章_24H/'
        })
      }
    });

    if (isSuccess) {
      $.log('分享回调完成。');

      return {
        isSuccess,
        msg: ''
      };
    }
    else {
      $.log(`分享回调失败！${response}`);

      return {
        isSuccess,
        msg: '分享回调失败！'
      };
    }
  }

  // 分享的每日奖励（貌似没啥用）
  async shareDailyReward(channelId) {
    const { isSuccess, data, response } = await requestApi('https://user-api.smzdm.com/share/daily_reward', {
      method: 'post',
      headers: this.getHeaders(),
      data: {
        token: this.token,
        channel_id: channelId
      }
    });

    if (isSuccess) {
      $.log(data.data.reward_desc);

      return {
        isSuccess,
        msg: data.data.reward_desc
      };
    }
    else {
      if (data) {
        $.log(data.error_msg);

        return {
          isSuccess,
          msg: data.error_msg
        };
      }
      else {
        $.log(`分享每日奖励请求失败！${response}`);

        return {
          isSuccess,
          msg: '分享每日奖励请求失败！'
        };
      }
    }
  }

  // 收藏
  async favorite({id, channelId, method}) {
    const { isSuccess, response } = await requestApi(`https://user-api.smzdm.com/favorites/${method}`, {
      method: 'post',
      headers: this.getHeaders(),
      data: {
        touchstone_event: this.getTouchstoneEvent({
          event_value: {
            aid: id,
            cid: channelId,
            is_detail: true
          },
          sourceMode: '我的_我的任务页',
          sourcePage: `Android/长图文/P/${id}/`,
          upperLevel_url: '个人中心/赚奖励/'
        }),
        token: this.token,
        id,
        channel_id: channelId
      }
    });

    if (isSuccess) {
      $.log(`${method} 收藏成功: ${id}`);
    }
    else {
      $.log(`${method} 收藏失败！${response}`);
    }

    return {
      isSuccess,
      response
    };
  }

  // 点赞
  async rating({id, channelId, method, type}) {
    const { isSuccess, response } = await requestApi(`https://user-api.smzdm.com/rating/${method}`, {
      method: 'post',
      headers: this.getHeaders(),
      data: {
        touchstone_event: this.getTouchstoneEvent({
          event_value: {
            aid: id,
            cid: channelId,
            is_detail: true
          },
          sourceMode: '栏目页',
          sourcePage: `Android//P/${id}/`,
          upperLevel_url: '栏目页///'
        }),
        token: this.token,
        id,
        channel_id: channelId,
        wtype: type
      }
    });

    if (isSuccess) {
      $.log(`${method} 点赞成功: ${id}`);
    }
    else {
      $.log(`${method} 点赞失败！${response}`);
    }

    return {
      isSuccess,
      response
    };
  }

  // 获取文章详情
  async getArticleDetail(id) {
    const { isSuccess, data, response } = await requestApi(`https://article-api.smzdm.com/article_detail/${id}`, {
      headers: this.getHeaders(),
      data: {
        comment_flow: '',
        hashcode: '',
        lastest_update_time: '',
        uhome: 0,
        imgmode: 0,
        article_channel_id: 0,
        h5hash: ''
      }
    });

    if (isSuccess) {
      return data.data;
    }
    else {
      $.log(`获取文章详情失败！${response}`);

      return false;
    }
  }

  getTouchstoneEvent(obj) {
    const defaultObj = {
      search_tv: 'f',
      sourceRoot: '个人中心',
      trafic_version: '113_a,115_b,116_e,118_b,131_b,132_b,134_b,136_b,139_a,144_a,150_b,153_a,179_a,183_b,185_b,188_b,189_b,193_a,196_b,201_a,204_a,205_a,208_b,222_b,226_a,228_a,22_b,230_b,232_b,239_b,254_a,255_b,256_b,258_b,260_b,265_a,267_a,269_a,270_c,273_b,276_a,278_a,27_a,280_a,281_a,283_b,286_a,287_a,290_a,291_b,295_a,302_a,306_b,308_b,312_b,314_a,317_a,318_a,322_b,325_a,326_a,329_b,32_c,332_b,337_c,341_a,347_a,349_b,34_a,351_a,353_b,355_a,357_b,366_b,373_B,376_b,378_b,380_b,388_b,391_b,401_d,403_b,405_b,407_b,416_a,421_a,424_b,425_b,427_a,436_b,43_j,440_a,442_a,444_b,448_a,450_b,451_b,454_b,455_a,458_c,460_a,463_c,464_b,466_b,467_b,46_a,470_b,471_b,474_b,475_a,484_b,489_a,494_b,496_b,498_a,500_a,503_b,507_b,510_bb,512_b,515_a,520_a,522_b,525_c,527_b,528_a,59_a,65_b,85_b,102_b,103_a,106_b,107_b,10_f,11_b,120_a,143_b,157_g,158_c,159_c,160_f,161_d,162_e,163_a,164_a,165_a,166_f,171_a,174_a,175_e,176_d,209_b,225_a,235_a,236_b,237_c,272_b,296_c,2_f,309_a,315_b,334_a,335_d,339_b,346_b,361_b,362_d,367_b,368_a,369_e,374_b,381_c,382_b,383_d,385_b,386_c,389_i,38_b,390_d,396_a,398_b,3_a,413_a,417_a,418_c,419_b,420_b,422_e,428_a,430_a,431_d,432_e,433_a,437_b,438_c,478_b,479_b,47_a,480_a,481_b,482_a,483_a,488_b,491_j,492_j,504_b,505_a,514_a,518_b,52_d,53_d,54_v,55_z1,56_z3,66_a,67_i,68_a1,69_i,74_i,77_d,93_a',
      tv: 'z1'
    };

    return JSON.stringify({...defaultObj, ...obj});
  }

  // 获取文章列表
  async getArticleList(num = 20) {
    const { isSuccess, data, response } = await requestApi('https://article-api.smzdm.com/ranking_list/articles', {
      headers: this.getHeaders(),
      data: {
        offset: 0,
        channel_id: 76,
        tab: 2,
        order: 0,
        limit: 20,
        exclude_article_ids: '',
        stream: 'a',
        ab_code: 'b'
      }
    });

    if (isSuccess) {
      // 取前 num 个做任务
      return data.data.rows.slice(0, num);
    }
    else {
      $.log(`获取文章列表失败: ${response}`);
      return [];
    }
  }
}



!(async () => {
  if (config === false) {
        $.log('\n请先设置 config.json 环境变量');

        return;
        }
        const users = config.userlist;

  let notifyContent = '';

  for (let i = 0; i < users.length; i++) {
    const cookie = users[i].rawcookie;

    if (!cookie) {
      continue;
    }


    if (i > 0) {
      $.log('\n延迟 10 秒执行\n');
      await $.wait(10000);
    }

    const sep = `\n****** 账号${users[i].username} ******\n`;

    $.log(sep);

    const bot = new SmzdmIntegralBot(users[i]);
    const msg = await bot.run();

    notifyContent += sep + msg + '\n';
    let notification=users[i].notification;
    await notify(notification,$.name, notifyContent);
  }

  $.log();
  
})().catch((e) => {
  $.log('', `❌ ${$.name}, 失败! 原因: ${e}!`, '')
}).finally(() => {
  $.done();
});
